package http;

import handle.MyHttpRequestHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class MyHttpServer {
    public static void main(String[] args) throws Exception{
        //创建主从线程池，如果阻塞用OioEventLoopGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Set<Channel> channels= Collections.synchronizedSet(new HashSet<>());
        try{
            //创建服务端的启动对象，设置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)//设置通道类型
                    .option(ChannelOption.SO_BACKLOG,128)//设置服务器端连接队列大小
                    .childOption(ChannelOption.SO_KEEPALIVE,true)//设置每个客户端连接保活
                    //添加Handler
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //处理http消息的编解码（netty提供）
                            socketChannel.pipeline().addLast(new HttpServerCodec());
                            //将多个 HTTP 消息片段聚合成一个完整的 HTTP 消息（netty）
                            socketChannel.pipeline().addLast(new HttpObjectAggregator(65536));
                            //自定义处理器
                            socketChannel.pipeline().addLast(new MyHttpRequestHandler(channels));
                        }
                    });
            System.out.println("-------服务端启动成功-----");
            //绑定端口号，启动服务端
            ChannelFuture future = bootstrap.bind(8080).sync();
            future.channel().closeFuture().sync();
        } finally {
            //优雅退出
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
